# -*- coding: utf-8 -*-
# @Function: 主控制程序
# @Description: 系统主控制文件，调用各个模块完成Excel导入和查询测试，是整个流程的入口点
# @Usage: 直接运行此文件可执行完整的数据导入和查询测试流程
# @Dependencies: importer.py, query_tester.py

import os
import sys
from pathlib import Path

# 将项目根目录加入 sys.path，确保可导入 D_db 包
REPO_ROOT = Path(__file__).resolve().parents[2]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

from D_db.io.importer import QAImporter
from D_db.tools.query_tester import QueryTester

def get_qa_final_path():
    """获取QA_final文件夹路径"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 修正路径计算，根目录是当前文件路径的上两级
    repo_root = Path(current_dir).parents[1]
    qa_final_path = os.path.join(repo_root, "C_filter", "QA_final")
    return qa_final_path

def import_data(importer):
    """导入Excel数据"""
    qa_final_path = get_qa_final_path()
    print(f"QA_final目录: {qa_final_path}")
    
    importer.db_manager.connect()  # 确保连接
    importer.db_manager.create_table() # 创建表
    success_count, total_count = importer.process_folder(qa_final_path)
    
    print(f"\nExcel导入结果: {success_count}/{total_count} 个文件成功导入")
    return success_count > 0

def test_queries():
    """测试查询"""
    test_questions = [
        "1995典型年的洪峰是多少？",
        "大伙房水库调度规程的主要起草人是谁"
    ]
    
    tester = QueryTester()
    for test_question in test_questions:
        print("\n" + "=" * 50)
        tester.test_query(test_question)

def main():
    """主函数"""
    print("=== Excel QA数据导入工具 ===")
    
    importer = QAImporter()
    try:
        # 步骤1: 导入Excel数据
        excel_success = import_data(importer)
        
        # 步骤2: 测试查询
        if excel_success:
            test_queries()
        else:
            print("\n由于导入失败，跳过查询测试")
        
    except Exception as e:
        print(f"\n程序执行失败: {e}")
    finally:
        importer.db_manager.close()

if __name__ == "__main__":
    main()